package com.example.bgmachine.bgmachine.modbus;

public class CRCUtils {
    public static byte[] makefcs(byte[] data)
    {
        int crc=0xFFFF;
        byte[] buf = new byte[data.length];// 存储需要产生校验码的数据
        byte[] bup=new byte[2];
        for (int i = 0; i < data.length; i++) {
            buf[i] = data[i];  //数据的复制
        }
        int len = buf.length;
        for (int pos = 0; pos < len; pos++) {
            if (buf[pos] < 0) {
                crc ^= (int) buf[pos] + 256; //^异或:用于位运算，每个位相同为0，不同为1

            } else {
                crc ^= (int) buf[pos];
            }
            for (int i = 8; i != 0; i--) {
                if ((crc & 0x0001) != 0) {
                    crc >>= 1;   //右移运算符
                    crc ^= 0xA001;
                } else
                    crc >>= 1;
            }
        }
        String c = Integer.toHexString(crc);
        if (c.length() == 4) {
            c = c.substring(2, 4) + c.substring(0, 2);
        } else if (c.length() == 3) {
            c = "0" + c;
            c = c.substring(2, 4) + c.substring(0, 2);
        } else if (c.length() == 2) {
            c = "0" + c.substring(1, 2) + "0" + c.substring(0, 1);
        }

        bup[0]=(byte)(Integer.parseInt(c.substring(0, 1), 16)+Integer.parseInt(c.substring(1,2), 16));
        bup[1]=(byte)(Integer.parseInt(c.substring(2, 3), 16)+Integer.parseInt(c.substring(3,4), 16));
        return bup;
    }

    public static int getCRC(byte[] bytes) {
        int CRC = 0x0000ffff;
        int POLYNOMIAL = 0x0000a001;

        int i, j;
        for (i = 0; i < bytes.length; i++) {
            CRC ^= ((int) bytes[i] & 0x000000ff);
            for (j = 0; j < 8; j++) {
                if ((CRC & 0x00000001) != 0) {
                    CRC >>= 1;
                    CRC ^= POLYNOMIAL;
                } else {
                    CRC >>= 1;
                }
            }
        }
        return CRC;
    }
}
